package com.ltedu.oss.controller;

import com.ltedu.common.contants.Constants;
import com.ltedu.common.enums.ErrorCodeEnum;
import com.ltedu.common.vo.Result;
import com.ltedu.oss.service.VideoService;
import com.ltedu.oss.storage.StorageFactory;
import com.ltedu.oss.utils.FileKit;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * @className: FileUploadController
 * @auther: Jerry
 * @date: 2020/11/26 14:10
 * @desctiption: TODO
 * @version: 1.0
 */
@RestController
@RequestMapping("/oss/file")
public class FileUploadController {

    private Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    @Autowired
    protected StorageFactory storageFactory;

    @Autowired
    private VideoService videoService;;

    /**
     * 文件上传
     *
     * @param file 文件
     * @return {@link Result}
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam(value = "file", required = false) MultipartFile file) {
        logger.info("FileUploadController.upload...");
        // 检查空
        if (null == file || file.isEmpty()) {
            return Result.fail(ErrorCodeEnum.NOT_FILE);
        }

        String fileName = file.getOriginalFilename();

        // 检查类型
        if (!FileKit.checkFileType(fileName)) {
            return Result.fail(ErrorCodeEnum.INVALID_FILE_TYPE);
        }

        // 检查大小
        String limitSize = Constants.STORAGE_LIMIT_SIZE;
        if (StringUtils.isBlank(limitSize)) {
            limitSize = "2";
        }
        if (file.getSize() > (Long.parseLong(limitSize) * 1024 * 1024)) {
            return Result.fail(ErrorCodeEnum.FILE_SIZE_LIMIT);
        }

        // 保存图片
        try {
            String path = storageFactory.get(Constants.STORAGE_SCHEME).store(file);
            return Result.ok(path);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    @PostMapping("/uploadVideo")
    public Result uploadVideo(@RequestParam(value = "file", required = false) MultipartFile file) {
        return Result.ok(videoService.uploadVideo(file));
    }
}
